<?php

declare(strict_types=1);

namespace App\Repository\User;

use App\Exception\BusinessException;
use App\Repository\BaseRepository;
use App\Repository\Cache\UserCacheRepository;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use App\Model\User;

class UserRepository extends BaseRepository
{
    #[Inject]
    private User $userModel;

    #[Inject]
    protected UserCacheRepository $userCacheRepository;

    /**
     * 创建用户
     * @param array $data
     * @return array
     */
    public function create(array $data): array
    {
        $user = $this->userModel->create($data);
        $user->setHidden(["password"]);
        return $user->toArray();
    }

    /**
     * 查找用户邮件
     * @param string $email
     * @return array
     */
    public function findByEmail(string $email): array
    {
        // 获取缓存数据
        $user = $this->userCacheRepository->getUserInfoByEmail($email);
        if (!$user) {
            $user = $this->userModel->where("email", $email)->select(["*"])->first();
            if ($user) {
                $user = $user->toArray();
                // 设置缓存数据
                $this->userCacheRepository->setUserInfoByEmail($email, $user);
                return $user;
            } else {
                return [];
            }
        } else {
            return $user;
        }
    }

    /**
     * 更新用户登录信息
     * @param int $user_id
     * @param string $ip
     */
    public function updateLoginInfo(int $user_id, string $ip): void
    {
        $this->userModel->where("id", $user_id)->update(["last_login_at" => Db::Raw("now()"), "last_login_ip" => $ip]);
    }

    /**
     * 根据用户id获取用户信息
     * @param string $id
     * @return array
     */
    public function getDataById(string $id): array
    {
        // 获取缓存数据
        $user = $this->userCacheRepository->getUserInfoById($id);
        if (!$user) {
            $user = $this->userModel->where("id", $id)->select(["*"])->first();
            if ($user) {
                $user = $user->toArray();
                // 设置缓存数据
                $this->userCacheRepository->setUserInfoById($id, $user);
                return $user;
            } else {
                return [];
            }
        } else {
            return $user;
        }
    }

    /**
     * 更新用户姓名和头像
     * name 不传则不更新name
     * @param $data array
     * @param $userId string
     * @param $userData array
     */
    public function updateNameAndAvatar(array $data, string $userId, array $userData): void
    {
        $obj = [];
        if (isset($data['name'])) {
            $obj['name'] = $data['name'];
            $userData['name'] = $data['name'];

            // 检查用户名是否已存在
            $exists = $this->userModel->where('name', $data['name'])
                ->where('id', '!=', $userId)
                ->exists();

            if ($exists) {
                throw new BusinessException('用户名已存在');
            }
        }

        $obj['avatar'] = $data['avatar'];
        $userData['avatar'] = $data['avatar'];
        // 数据库跟新
        $this->userModel->where("id", $userId)->update($obj);

        // 跟新redis 数据
        $this->userCacheRepository->setUserInfoById($userId, $userData);

    }

}